<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of BUser
 *
 * @author ID59C
 */
class BUser extends BEntityWithGroup {

    const All_User = 'all_user';
    const Not_Exist_User = "not_exist_user";

    //protected $id = null;
    public $userId = null;
    public $userName = null;
    public $email = null;
    protected $password = null;
    protected $birthday = BEntity::String_Any;
    protected $profile = null;
    public $_identity = null;
    protected $personalSpace = null;
    protected $salt = null;
    protected $cart = null;
    public $status = null;
    public $myid = null;

    //put your code here
    public function __construct($id = NULL) {
        $this->load($id);

        /*
          if ($id == NULL) {
          $webUser = $this->getWebUser();
          if ($webUser != NULL)
          $this->load($webUser->getId());
          } else {
          $this->load($id);
          }
         * 
         */
    }

    public function getId($data = null) {
        if ($this->id == NULL)
            $this->id = $this->getWebUser()->getId();
        return $this->id;
    }

    public function getUserIdentity() {
        return $this->_identity;
    }

    public function getUserId($data = NULL) {
        return $this->userId;
    }

    public function getUserEmail($data = null) {
        return $this->email;
    }

    public function getUserSalt($data = null) {
        return $this->salt;
    }

    public function getUserActivationKey($data = null) {
        return $this->myid;
    }

    public function getUserStatus($data = null) {
        return $this->status;
    }

    public function getName($data = NULL) {
        $name = $this->userName == NULL ? $this->userId : $this->userName;
        return $name;
    }

    public function setUserIdentity($data = NULL) {
        return $this->_identity = $data;
    }

    public function getPersonalSpace($context = NULL) {

//        $savedPersonSpaceId = Blyn::app()->getCurrentUser()->getContextVariable('myPersonalSpaceId');
//
//        //first try to get personal id from context variable
//        if ($savedPersonSpaceId != NULL && is_numeric($savedPersonSpaceId) && $savedPersonSpaceId > 0)
//            return new BSpace($savedPersonSpaceId);

        if ($this->personalSpace == NULL) {

            //$spacesWithRoles = BRole::findAll(array('userId' => $this->getId()));
            $spacesWithRoles = BSpace::findUserSpaces($this);
            //$spacesWithRoles = $this->getUserSpaces();
            foreach ($spacesWithRoles as $spaceId => $roleList) {
                $space = new BSpace($spaceId);
                if (Blyn::app()->getActiveSpace() == NULL)
                    Blyn::app()->setActiveSpace($space);
                $adminRole = $space->getSpaceEngine()->getRole(BRole::Role_App_Admin);
                $user = Blyn::app()->getCurrentUser();
                if ($space->getSpaceType()->getName() == BSpaceGroup::Group_SpaceType_PersonalSpace && $user->isMemberOf($adminRole)) {
                    $this->personalSpace = $space;
                    break;
                }
            }
        }

        if ($this->personalSpace instanceof BSpace) {
            Blyn::app()->getCurrentUser()->addContextVariable('myPersonalSpaceId', $this->personalSpace->getId());
            return $this->personalSpace;
        }
        return FALSE;
    }

    public function getUserSpaces($context = array()) {

        $cacheManager = Blyn::app()->getCacheManager();

        $spaces = $cacheManager->getCache('userSpaces');

        if (is_array($spaces) && $spaces != NULL) {
            $adminSpacesCache = isset($spaces['adminSpacesCache']) ? $spaces['adminSpacesCache'] : array();
            $memberSpacesCache = isset($spaces['memberSpacesCache']) ? $spaces['memberSpacesCache'] : array();
            $customerSpacesCache = isset($spaces['customerSpacesCache']) ? $spaces['customerSpacesCache'] : array();

            $adminSpaces = array();

            foreach ($adminSpacesCache as $spaceId => $value) {
                foreach ($value as $roleId => $value) {
                    $adminSpaces[$spaceId][$roleId] = new BRole($roleId);
                }
            }

            $memberSpaces = array();

            foreach ($memberSpacesCache as $spaceId => $value) {
                foreach ($value as $roleId => $value) {
                    $memberSpaces[$spaceId][$roleId] = new BRole($roleId);
                }
            }

            $customerSpaces = array();

            foreach ($customerSpacesCache as $spaceId => $value) {
                foreach ($value as $roleId => $value) {
                    $customerSpaces[$spaceId][$roleId] = new BRole($roleId);
                }
            }

            if (!($adminSpaces == NULL && $customerSpaces == NULL && $memberSpaces == NULL))
                return array('adminSpaces' => $adminSpaces, 'memberSpaces' => $memberSpaces, 'customerSpaces' => $customerSpaces);
        }

        $context['userId'] = $this->getId();

        $userRoles = BRole::findUserRoles($this);

        //$rolesWithContext = BRole::findAll($context, TRUE);

        $adminSpaces = array();
        $memberSpaces = array();
        $customerSpaces = array();
        $adminSpacesCache = array();
        $memberSpacesCache = array();
        $customerSpacesCache = array();

        if ($userRoles != FALSE) {
            foreach ($userRoles as $role) {
                if ($role instanceof BRole) {
                    $spaceId = $role->spaceId;
                    //$app = BApp::buildAppById($role->appId);
                    if ($role->isChildOf(BRole::Role_App_customer) || $role->getName() == BRole::Role_App_customer) {
                        if (!isset($customerSpaces[$spaceId]))
                            $customerSpaces[$spaceId] = array();
                        $customerSpaces[$spaceId][$role->getId()] = $role;
                        $customerSpacesCache[$spaceId][$role->getId()] = $role->getId();
                    }

                    if ($role->isChildOf(BRole::Role_App_Member) || $role->getName() == BRole::Role_App_Member) {
                        if (!isset($memberSpaces[$spaceId]))
                            $memberSpaces[$spaceId] = array();
                        $memberSpaces[$spaceId][$role->getId()] = $role;
                        $memberSpacesCache[$spaceId][$role->getId()] = $role->getId();
                    }

                    if ($role->isChildOf(BRole::Role_App_Admin) || $role->getName() == BRole::Role_App_Admin) {
                        if (!isset($adminSpaces[$spaceId]))
                            $adminSpaces[$spaceId] = array();
                        $adminSpaces[$spaceId][$role->getId()] = $role;
                        $adminSpacesCache[$spaceId][$role->getId()] = $role->getId();
                    }
                }
            }
        }

        Blyn::app()->getCacheManager()->addCache('userSpaces', array(
            'adminSpacesCache' => $adminSpacesCache,
            'memberSpacesCache' => $memberSpacesCache,
            'customerSpacesCache' => $customerSpacesCache));

        return array('adminSpaces' => $adminSpaces, 'memberSpaces' => $memberSpaces, 'customerSpaces' => $customerSpaces);
    }

    public function getUserSpacesReloaded($context = array()) {
        $userID = $this->getId();
        if ($userID != NULL && $userID > 0) {
            $userRoles = BRole::findUserRolesReloaded($userID, NULL, NULL, true);
            $adminSpaces = array();
            $memberSpaces = array();
            $customerSpaces = array();
            $adminSpacesCache = array();
            $memberSpacesCache = array();
            $customerSpacesCache = array();

            if ($userRoles != FALSE) {
                foreach ($userRoles as $role) {
                    if ($role instanceof BRole) {
                        $spaceId = $role->spaceId;
                        //$app = BApp::buildAppById($role->appId);
                        if ($role->isChildOf(BRole::Role_App_customer) || $role->getName() == BRole::Role_App_customer) {
                            if (!isset($customerSpaces[$spaceId]))
                                $customerSpaces[$spaceId] = array();
                            $customerSpaces[$spaceId][$role->getId()] = $role;
                            $customerSpacesCache[$spaceId][$role->getId()] = $role->getId();
                        }

                        if ($role->isChildOf(BRole::Role_App_Member) || $role->getName() == BRole::Role_App_Member) {
                            if (!isset($memberSpaces[$spaceId]))
                                $memberSpaces[$spaceId] = array();
                            $memberSpaces[$spaceId][$role->getId()] = $role;
                            $memberSpacesCache[$spaceId][$role->getId()] = $role->getId();
                        }

                        if ($role->isChildOf(BRole::Role_App_Admin) || $role->getName() == BRole::Role_App_Admin) {
                            if (!isset($adminSpaces[$spaceId]))
                                $adminSpaces[$spaceId] = array();
                            $adminSpaces[$spaceId][$role->getId()] = $role;
                            $adminSpacesCache[$spaceId][$role->getId()] = $role->getId();
                        }
                    }
                }
            }

            Blyn::app()->getCacheManager()->addCache('userSpaces', array(
                'adminSpacesCache' => $adminSpacesCache,
                'memberSpacesCache' => $memberSpacesCache,
                'customerSpacesCache' => $customerSpacesCache));

            return array('adminSpaces' => $adminSpaces, 'memberSpaces' => $memberSpaces, 'customerSpaces' => $customerSpaces);
        } else
            $this->getUserSpaces();
    }

    public function addRole($role, $data = NULL) {

        $spaceId = isset($data['spaceId']) ? $data['spaceId'] : NULL;
        $appId = isset($data['appId']) ? $data['appId'] : NULL;
        $userId = isset($data['userId']) ? $data['userId'] : NULL;

        $attributes = array();
        if ($userId == NULL)
            $userId = $this->getId();
        $attributes['user_id'] = $userId;

        if ($role instanceof BRole)
            $roleId = $role->getId();
        if (is_numeric($role))
            $roleId = $role;

        if (is_array($role))
            $roleId = $role['id'];

        if (!is_numeric($roleId))
            return FALSE;

        $attributes['role_id'] = $roleId;
        if ($spaceId != NULL)
            $attributes['space_id'] = $spaceId;
        if ($appId != NULL)
            $attributes['app_id'] = $appId;

        $mUserRole = BMRoleUser::model()->findByAttributes($attributes);

        if ($mUserRole instanceof BMRoleUser)
            return;

        $mUserRole = new BMRoleUser();

        $mUserRole->role_id = $roleId;
        $mUserRole->user_id = $userId;
        if ($spaceId != NULL)
            $mUserRole->space_id = $spaceId;
        if ($appId != NULL)
            $mUserRole->app_id = $appId;

        $mUserRole->save();
        Blyn::app()->getCacheManager()->addCacheEvent(BCacheManager::Event_Change_User_Role, TRUE);
    }

    public function rejectMember($role, $data = NULL) {
        
    }

    public function acceptMember($role, $data = NULL) {
        //add record into bln_role_user table
        $this->addRole($role, $data);
    }

    public function removeRole($role, $data = NULL) {
        $spaceId = isset($data['spaceId']) ? $data['spaceId'] : NULL;
        $appId = isset($data['appId']) ? $data['appId'] : NULL;
        $userId = isset($data['userId']) ? $data['userId'] : NULL;

        $attributes = array();
//        $attributes['user_id'] = $this->getId();
        if ($role instanceof BRole)
            $roleId = $role->getId();
        if (is_numeric($role))
            $roleId = $role;

        if (is_array($role))
            $roleId = $role['id'];

        if (!is_numeric($roleId))
            return FALSE;

        $attributes['_id'] = $roleId;
        if ($spaceId != NULL)
            $attributes['space_id'] = $spaceId;
        if ($appId != NULL)
            $attributes['app_id'] = $appId;
        if ($userId != NULL)
            $attributes['user_id'] = $userId;

        $mUserRole = BMRoleUser::model()->findByAttributes($attributes);

//        if ($mUserRole instanceof BMRoleUser)
        $mUserRole->delete();
    }

    public function createSpace($data) {

        $config = $data;

        //$db = Blyn::app()->getAppDb();

        if (is_string($data))
            $sName = $data;

        $sName = isset($config['SpaceName']) ? $config['SpaceName'] : 'Not specify name';
        $sMyId = isset($config['MySpaceId']) ? $config['MySpaceId'] : 'Not specify ID';
        $sType = isset($config['SpaceType']) ? $config['SpaceType'] : BSpaceGroup::Group_SpaceType_NormalSpace;
        $sCategory = isset($config['SpaceCategory']) ? $config['SpaceCategory'] : BSpaceGroup::Group_Category_General;

        //$user = $this;

        $newSpace = new BSpace();

        $newSpace->name = $sName;
        $newSpace->myId = $sMyId;

        //$newSpace->type = $sType;
        //$newSpace->category = $sCategory;

        $newSpace->save($data);

        if ($newSpace instanceof BSpace && Blyn::app()->getActiveSpace() == NULL) {
            Blyn::app()->setActiveSpace($newSpace);
        }

        $spaceCooker = new BSpaceCooker();
        $spaceCooker->addSpaceInfo(array('name' => $sName, 'myId' => $sMyId, 'spaceId' => $newSpace->getId()), $sType);

        //add a SpaceEngine to Space
        $sEngine = new BSpaceEngine();

        //$sEngine->addRolesToSpace($role);

        $newSpace->addApp($sEngine);

        $sEngine->setCurrentSpace($newSpace);

        $role = $sEngine->getRole(BRole::Role_Space_Admin);

        $role->addMember($this);

        //this function add cache event, that will cause reload of userSpaces data in cache
        Blyn::app()->getCacheManager()->addCacheEvent(BCacheManager::Event_AddNewSpace, TRUE);

        //$this->addRole($role, array('spaceId' => $newSpace->getId()));

        return $newSpace;
    }

    public function joinToSpace($space, $roles = NULL) {

        $spaceId = is_numeric($space) ? $space : NULL;

        if ($space instanceof BSpace)
            $spaceId = $space->getId();

        if ($roles == NULL)
            $role = Blyn::app()->getActiveApp()->getRole(BRole::Role_Space_customer);

        if ($spaceId != NULL && $spaceId > 0 && $role instanceof BRole) {
            $this->addRole($role, array('spaceId' => $spaceId));
            return;
        }
        return FALSE;
    }

    public function exitSpace($space) {

        if (is_numeric($space))
            $spaceId = $space;

        if ($space instanceof BSpace)
            $spaceId = $space->getId();

        if ($spaceId > 0)
            $roles = BRole::findAll(array('spaceId' => $spaceId, 'userId' => $this->getId()));

        foreach ($roles as $role) {
            $this->removeRole($role);
        }

        return;
    }

    /**
     * load obj from data store
     * @param type $id
     */
    /*
      public function load($data = NULL) {

      if (is_numeric($data) && $data > 0) {
      $this->id = $data;
      }

      if ($this->id != null && $this->id > 0) {
      $mUser = BMUser::model()->findByPk($this->id);
      $this->userId = $mUser->userid;
      $this->userName = $mUser->username;
      $this->password = $mUser->password;
      $this->salt = $mUser->salt;
      $this->email = $mUser->email;
      $this->birthday = $mUser->password;
      $this->profile = unserialize($mUser->profile);
      }

      return FALSE;
      }
     * 
     */

    /**
     * save data to data store
     * @param type $data
     */
    public function save($data = NULL) {
        //return parent::save($data);
        //create new user

        if ($this->getId() == NULL || $this->getId() < 0) {
            if (isset($data['email']) && isset($data['password'])) {
                $userId = isset($data['userId']) ? $data['userId'] : $data['email'];
                $email = $data['email'];
                $password = $data['password'];
                $userName = isset($data['userName']) ? $data['userName'] : $email;
                $birthday = isset($data['birthday']) ? $data['birthday'] : "1900-01-01";
                $salt = $this->blowfishSalt();
                $password = crypt($password, $salt);
                $profile = isset($data['profile']) ? $data['profile'] : array();
                $myId = isset($data['myid']) ? $data['myid'] : sha1(mt_rand(10000, 99999) . $data['email']);
//                $status = isset($data['status']) ? $data['status'] : 0;

                $this->email = $email;
                $this->userId = $userId;
                $this->password = $password;
                $this->userName = $userName;
                $this->salt = $salt;
                $this->birthday = $birthday;
                $this->profile = serialize($profile);
                $this->myid = $myId;

                $id = parent::save();
                return $id;
            }
        } else {
            //change password only
            if (is_array($data)) {

                if (isset($data['password'])) {
                    $password = crypt($data['password'], $this->getUserSalt());
                    $this->password = $password;
                }

                if (isset($data['birthday']))
                    $this->birthday = $data['birthday'];

                if (isset($data['userId']))
                    $this->userId = $data['userId'];

                if (isset($data['userName']))
                    $this->userName = $data['userName'];

                if (isset($data['email'])) {
                    $this->email = $data['email'];
                }

                if (isset($data['myid'])) {
                    $this->myid = $data['myid'];
                }

                $id = parent::save();
                return $id;
            }
        }
    }

    public function load($data = NULL, $context = NULL) {
        parent::load($data, $context);
    }

    public static function register($loginId, $password, $data = NULL) {

        $attributes = array();

        $attributes['salt'] = self::blowfishSalt(6);
        $attributes['password'] = $password;
        $attributes['userid'] = $loginId;
        //by default, set userId as userName
        $attributes['username'] = $loginId;
        if (isset($data['userName']))
            $attributes['username'] = $data['userName'];
        if (isset($data['email']))
            $attributes['email'] = $data['email'];
        if (isset($data['birthday']))
            $attributes['birthday'] = $data['birthday'];
        if (isset($data['profile']))
            $attributes['profile'] = $data['profile'];
        $attributes['myid'] = sha1(mt_rand(10000, 99999) . $data['email']);

        $user = new BUser();

        $user->save($attributes);
        return TRUE;

        //if (Blyn::app()->getCurrentUser() == NULL)
//        Blyn::app()->setCurrentUser($user);
//
//        //add personalSpace
//        if ($user->id != FALSE) {
//
//            $personalSpaceStr = Yii::t('site', '_personalSpace');
//            $userName = $user->getName();
//            $pSpace = $user->createSpace(array('SpaceName' => $userName . $personalSpaceStr, 'SpaceType' => BSpaceGroup::Group_SpaceType_PersonalSpace));
//
//            //$pSpace = BSpace::createSpace(array("User" => $this, "SpaceName" => $userId . "_personalSpace",
//            //            'SpaceType' => BSpace::PERSONALSpaceTYPE));            
//            //$pSpace = BSpace::createSpace(array("User" => $this, "SpaceName" => $userId . "_personalSpace",
//            //            'SpaceType' => BSpace::PERSONALSpaceTYPE));
//            //add default app into personalSpace      
//            $pApp = new BPersonalApp();
//
//            $pSpace->addApp($pApp);
//
//            $role = $pApp->getRole(BRole::Role_App_Admin);
//            $role->addMember($user);
//            //$pSpace->getSpaceEngine()->doOperation(BSpaceEngine::ADDAppOPERATION, array('Space' => $pSpace, 'App' => $pApp));
//
//            return TRUE;
//            //      $this->login($loginId, $email, $password, $duration);
//        }
//        return FALSE;
    }

    public static function registerWechat($loginId, $password, $data = NULL) {

        $attributes = array();

        $attributes['salt'] = self::blowfishSalt(6);
        $attributes['password'] = $password;
        $attributes['userid'] = $loginId;
        //by default, set userId as userName
        $attributes['username'] = $loginId;
        if (isset($data['userName']))
            $attributes['username'] = $data['userName'];
        if (isset($data['email']))
            $attributes['email'] = $data['email'];
        if (isset($data['birthday']))
            $attributes['birthday'] = $data['birthday'];
        if (isset($data['profile']))
            $attributes['profile'] = $data['profile'];
        $attributes['myid'] = 'activated';

        $user = new BUser();

        $user->save($attributes);

        //below adjust userid for wx user
        $userId = 'D' . (20081205 + $user->getId());
        $newAttr = array();
        $newAttr['userId'] = $userId;
        if (!(isset($attributes['userName']) && $attributes['userName'] == $loginId)) {
            $newAttr['userName'] = $userId;
        }
        //if (!isset($attributes['email'])) {
        $newAttr['email'] = $userId . '@billyn.net';
        //}

        $user->save($newAttr);

        if (Blyn::app()->getCurrentUser() == NULL)
            Blyn::app()->setCurrentUser($user);
        else {
            if (Blyn::app()->getCurrentUser()->getId() == NULL)
                Blyn::app()->setCurrentUser($user);
        }


        //add personalSpace
        if ($user->id != FALSE) {

            $personalSpaceStr = Yii::t('site', '_personalSpace');
            $userName = $user->getName();
            $pSpace = $user->createSpace(array('SpaceName' => $userName . $personalSpaceStr, 'MySpaceId' => $userName . '_space', 'SpaceType' => BSpaceGroup::Group_SpaceType_PersonalSpace));

            //$pSpace = BSpace::createSpace(array("User" => $this, "SpaceName" => $userId . "_personalSpace",
            //            'SpaceType' => BSpace::PERSONALSpaceTYPE));            
            //$pSpace = BSpace::createSpace(array("User" => $this, "SpaceName" => $userId . "_personalSpace",
            //            'SpaceType' => BSpace::PERSONALSpaceTYPE));
            //add default app into personalSpace      
            $pApp = new BPersonalApp();

            $pSpace->addApp($pApp);

            $role = $pApp->getRole(BRole::Role_App_Admin);
            $role->addMember($user);
            //$pSpace->getSpaceEngine()->doOperation(BSpaceEngine::ADDAppOPERATION, array('Space' => $pSpace, 'App' => $pApp));

            return $user;
            //      $this->login($loginId, $email, $password, $duration);
        }
        return FALSE;
    }

    public static function activate($user) {
        $attributes = array();
        $attributes['myid'] = 'activated';
        $user->save($attributes);

        Blyn::app()->setCurrentUser($user);

        //add personalSpace
        if ($user->id != FALSE) {

            $personalSpaceStr = Yii::t('site', '_personalSpace');
            $userName = $user->getName();
            $pSpace = $user->createSpace(array('SpaceName' => $userName . $personalSpaceStr, 'MySpaceId' => $userName . '_space', 'SpaceType' => BSpaceGroup::Group_SpaceType_PersonalSpace));

            $pApp = new BPersonalApp();
            $pSpace->addApp($pApp);

            $role = $pApp->getRole(BRole::Role_App_Admin);
            $role->addMember($user);

//            $this->login($user->userid, $user->email, $user->password, $duration);
            return TRUE;
        }
        return FALSE;
    }

    private static function blowfishSalt($cost = 8) {
        if (!is_numeric($cost) || $cost < 4 || $cost > 31) {
            throw new Exception("cost parameter must be between 4 and 31");
        }
        $rand = array();
        for ($i = 0; $i < 8; $i += 1) {
            $rand[] = pack('S', mt_rand(0, 0xffff));
        }
        $rand[] = substr(microtime(), 2, 6);
        $rand = sha1(implode('', $rand), true);
        $salt = '$2a$' . sprintf('%02d', $cost) . '$';
        $salt .= strtr(substr(base64_encode($rand), 0, 22), array('+' => '.'));
        return $salt;
    }

    /**
     *
     * @return CWebUser
     */
    public function getWebUser() {
        return yii::app()->user;
    }

    public function authenticate($loginId, $password) {

        if ($loginId != NULL)
            $this->userId = $loginId;
        if ($password != NULL)
            $this->password = $password;

        if ($this->_identity === null) {
            $this->_identity = new BUserIdentity($loginId, $password);
            $this->_identity->authenticate();
            return $this->_identity->errorCode;
        }
        return FALSE;
    }

    public static function login($loginId, $password, $duration) {

        $user = new BUser();

        $errorCode = $user->authenticate($loginId, $password);

        if ($errorCode === BUserIdentity::ERROR_NONE) {
            $user->getWebUser()->login($user->getUserIdentity(), $duration);
            if ($user->id == NULL)
                $user->load($user->getUserIdentity()->getId());
            return $errorCode;
        } else if ($errorCode == -1) {
            return $errorCode;
        } else
            return $errorCode; //false;
    }

    public function addContextVariable($name, $value, $scope = null, $type = NULL) {

        $contextObj = Blyn::app()->getContextObj();

        return $contextObj->addContextVariable(BContextObj::Scope_User, $name, $value);
    }

    public function getContextVariable($name, $scope = NULL, $type = NULL) {

        return Blyn::app()->getContextObj()->getContextVariable(BContextObj::Scope_User, $name);
    }

    public function getCache($id) {
        $cacheId = 'user' . $this->getId() . '_' . $id;
        return yii::app()->cache->get($cacheId);
    }

    public function setCache($id, $value, $expire = 0, $dependency = NULL) {
        $id = 'user' . $this->getId() . '_' . $id;
        return yii::app()->cache->set($id, $value, $expire, $dependency);
    }

    public function resetContextVariable($name = null, $scope = NULL, $scopeType = null) {

        return Blyn::app()->getContextObj()->resetContextVariable(BContextObj::Scope_User, $name);
    }

    public function validatePassword($password) {
        $salt = $this->salt;
        $tt = crypt($password, $salt);
        if ($this->password === crypt($password, $salt))
            return TRUE;
        return FALSE;
    }

    public function changePassword($oldPassword, $newPassword) {
        if ($this->validatePassword($oldPassword)) {
            $this->password = crypt($newPassword, $this->getUserSalt());
            $this->save();
            return TRUE;
        }
        return FALSE;
    }

    public function isActivated() {
        if ($this->myid == 'activated' || $this->myid == NULL)
            return TRUE;
        return FALSE;
    }

    /**
     * this function will check whether user have role belong to roles
     * @param type $roles
     * @param type $user
     */
    public function isMemberOfRoles($roles, $recursive = FALSE, $context = NULL, $userOrCircle = NULL) {

        if (is_array($roles) && $roles != NULL) {

            foreach ($roles as $role) {
                if ($role->getId() == BRole::find(BRole::All_Roles)->getId())
                    return TRUE;
            }

            $userRoles = array();

            if ($userOrCircle == NULL) {
                $user = $this;
                $userRoles = BRole::findUserRoles($user, $context, $recursive);
            }

            if ($user instanceof BCircle) {
                $userRoles = BRole::findCircleRoles($userOrCircle, $context, $recursive);
            }

            foreach ($userRoles as $uRole) {
                foreach ($roles as $role) {
                    if ($uRole instanceof BRole) {
                        if ($uRole->isChildOf($role) || $uRole->getId() == $role->getId())
                            return TRUE;
                    }
                }
            }
        }

        return FALSE;
    }

    public function isMemberOfRole($role, $recursive = FALSE, $context = NULL, $userOrCircle = NULL) {

        if ($role->getId() == BRole::find(BRole::All_Roles)->getId())
            return TRUE;


        $userRoles = array();

        if ($userOrCircle == NULL) {
            $user = $this;
            $userRoles = BRole::findUserRoles($user, $context, $recursive);
        }

        if ($user instanceof BCircle) {
            $userRoles = BRole::findCircleRoles($userOrCircle, $context, $recursive);
        }

        foreach ($userRoles as $uRole) {
            if ($uRole instanceof BRole) {
                if ($uRole->isChildOf($role) || $uRole->getId() == $role->getId())
                    return TRUE;
            }
        }

        return FALSE;
    }

    public static function find($context) {
        if (is_string($context) && $context != NULL)
            $context = array('userId' => $context);

        $user = parent::find($context);

        if ($user instanceof BUser) {
            //if(BUser::filterEntityByContext($user, $context))
            return $user;
        }

        return NULL;
    }

    public function getGroupClass($data = NULL) {
        return 'BCircle';
    }

    public function getCart($data = NULL) {
        if ($this->cart == NULL) {
            $this->cart = new BCart();
        }
        return $this->cart;
    }

}

?>
